package com.uinnova.product.eam.service.impl;

import com.binary.core.util.BinaryUtils;
import com.uinnova.product.eam.comm.exception.BusinessException;
import com.uinnova.product.eam.comm.model.es.EamMultiModelHierarchy;
import com.uinnova.product.eam.model.EamArtifactVo;
import com.uinnova.product.eam.model.cj.vo.DlvrTemplateReq;
import com.uinnova.product.eam.model.cj.vo.DlvrTemplateVO;
import com.uinnova.product.eam.model.dto.SysArtifactVo;
import com.uinnova.product.eam.model.dto.SysModelVo;
import com.uinnova.product.eam.model.dto.SysTemplateDto;
import com.uinnova.product.eam.service.EamCategorySvc;
import com.uinnova.product.eam.service.IEamArtifactSvc;
import com.uinnova.product.eam.service.IModuleSvc;
import com.uinnova.product.eam.service.cj.service.DeliverableTemplateService;
import com.uinnova.product.eam.service.cj.service.PlanDesignInstanceService;
import com.uinnova.product.eam.service.es.BmMultiModelHierarchyDao;
import com.uinnova.product.eam.service.es.EamCategoryDesignDao;
import com.uino.bean.permission.base.SysModule;
import com.uino.bean.permission.base.SysUser;
import com.uino.bean.sys.base.ESDictionaryItemInfo;
import com.uino.bean.sys.query.ESDictionaryItemSearchBean;
import com.uino.dao.permission.rlt.ESRoleModuleRltSvc;
import com.uino.service.permission.microservice.impl.ModuleSvc;
import com.uino.service.sys.microservice.IDictionarySvc;
import com.uino.util.sys.SysUtil;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ModuleSvcImpl implements IModuleSvc {

    private static final String _DEFAULT_BUTTON = "页面查看";
    private static final String DICT_ARTIFACT_TYPE = "制品类型分类";

    private static final String DICT_MODEL_TYPE = "建模工艺类型";

    @Resource
    private IEamArtifactSvc iEamArtifactSvc;

    @Resource
    BmMultiModelHierarchyDao hierarchyDao;

    @Autowired
    private EamCategorySvc categorySvc;

    @Autowired
    private IDictionarySvc dictSvc;

    @Value("${http.resource.space}")
    private String rsmSlaveRoot;

    @Autowired
    ESRoleModuleRltSvc roleModuleRltSvc;

    @Autowired
    private DeliverableTemplateService templateService;

    @Autowired
    private PlanDesignInstanceService planService;

    @Autowired
    private ModuleSvc moduleSvc;

    @Resource
    private EamCategoryDesignDao categoryDesignDao;

    @Override
    public SysModule eamSaveModule(SysModule saveDto) {
        //检查参数
        saveDto = saveDto == null ? new SysModule() : saveDto;
        SysUser userInfo = SysUtil.getCurrentUserInfo();
        saveDto.setDomainId(userInfo.getDomainId());
        SysModule sysModule = moduleSvc.saveModule(saveDto);
        //moduleType:"0:菜单, 1:按钮 2 资产仓库小组，3：资产仓库目录"
        if (saveDto.getModuleType() == 3 && BinaryUtils.isEmpty(saveDto.getId())) {
            Long topCategory = categorySvc.createTopCategory(sysModule);
        }
        return sysModule;
    }

    @Override
    public List<SysArtifactVo>  queryDiagramType() {
        /**
         * 整体查询一下字典表，组成一个map<id,name>
         *     再查询一下全量制品。根据类型分类--分组；Map<类型分类，制品名称>
         *     再组装一个map
         */
        ESDictionaryItemSearchBean bean = new ESDictionaryItemSearchBean();
        bean.setDomainId(1L);
        bean.setDictName(DICT_ARTIFACT_TYPE);
        List<ESDictionaryItemInfo> dictInfo = dictSvc.searchDictItemListByBean(bean);
        List<SysArtifactVo> artifactVoList = new ArrayList<>();
        if(!BinaryUtils.isEmpty(dictInfo)){
            Map<String, String> dictMap = dictInfo.stream().collect(Collectors.toMap(each -> each.getAttrs().get("ID"), each -> each.getAttrs().get("名称"), (k1, k2) -> k1));
            Set<String> stringIds = dictMap.keySet();
            List<Integer> dictIds = stringIds.stream().map(Integer::parseInt).collect(Collectors.toList());
            List<EamArtifactVo> artifactVos = iEamArtifactSvc.queryByType(dictIds);
            if(BinaryUtils.isEmpty(artifactVos)){
                return new ArrayList<>();
            }
            List<EamArtifactVo> filterArtifact = artifactVos.stream().filter(each -> each.getDataStatus() == 1).filter(each -> each.getReleaseState() == 1).collect(Collectors.toList());
            if(!BinaryUtils.isEmpty(filterArtifact)){
                SysArtifactVo vo = new SysArtifactVo();
                vo.setId(0);
                vo.setName("自由视图");
                List<EamArtifactVo>  voList = new ArrayList<>();
                EamArtifactVo  eamArtifactVo = new EamArtifactVo();
                eamArtifactVo.setId(0L);
                eamArtifactVo.setArtifactName("自由视图");
                voList.add(eamArtifactVo);
                vo.setVoList(voList);
                artifactVoList.add(vo);
                Map<Integer, List<EamArtifactVo>> artifactMap = filterArtifact.stream().collect(Collectors.groupingBy(EamArtifactVo::getTypeClassification));
                for (Integer type : artifactMap.keySet()) {
                    SysArtifactVo sysVo = new SysArtifactVo();
                    sysVo.setId(type);
                    sysVo.setName(dictMap.get(type.toString()));
                    List<EamArtifactVo> eamArtifactVos = artifactMap.get(type);
                    List<EamArtifactVo> sortArtifact = eamArtifactVos.stream().sorted(Comparator.comparing(EamArtifactVo::getCreateTime)).collect(Collectors.toList());
                    sysVo.setVoList(sortArtifact);
                    artifactVoList.add(sysVo);
                }
            }
        }
        if(!BinaryUtils.isEmpty(artifactVoList)){
            return artifactVoList.stream().sorted(Comparator.comparing(SysArtifactVo::getId)).collect(Collectors.toList());
        }
        return  new ArrayList<>();
    }

    @Override
    public List<SysModelVo> queryModuleType() {
        ESDictionaryItemSearchBean bean = new ESDictionaryItemSearchBean();
        bean.setDomainId(1L);
        bean.setDictName(DICT_MODEL_TYPE);
        List<ESDictionaryItemInfo> dictInfo = dictSvc.searchDictItemListByBean(bean);
        List<SysModelVo> voList = new ArrayList<>();
        if(!BinaryUtils.isEmpty(dictInfo)){
            Map<String, String> dictMap = dictInfo.stream().collect(Collectors.toMap(each -> each.getAttrs().get("ID"), each -> each.getAttrs().get("名称"), (k1, k2) -> k1));
            Set<String> stringIds = dictMap.keySet();
            List<Integer> dictIds = stringIds.stream().map(Integer::parseInt).collect(Collectors.toList());
            BoolQueryBuilder query = new BoolQueryBuilder();
            query.must(QueryBuilders.termQuery("releaseState",1)).
                    must(QueryBuilders.termQuery("dataStatus",1)).
                    must(QueryBuilders.termsQuery("modelType",dictIds));
            List<EamMultiModelHierarchy> listByQuery = hierarchyDao.getListByQuery(query);
            if(!BinaryUtils.isEmpty(listByQuery)){
                Map<Integer, List<EamMultiModelHierarchy>> modelMap = listByQuery.stream().collect(Collectors.groupingBy(EamMultiModelHierarchy::getModelType));
                for (Integer type : modelMap.keySet()) {
                    SysModelVo vo = new SysModelVo();
                    vo.setID(type);
                    vo.setName(dictMap.get(type.toString()));
                    List<EamMultiModelHierarchy> hierarchies = modelMap.get(type);
                    List<EamMultiModelHierarchy> sortModel = hierarchies.stream().sorted(Comparator.comparing(EamMultiModelHierarchy::getCreateTime)).collect(Collectors.toList());
                    vo.setVoList(sortModel);
                    voList.add(vo);
                }
            }
        }
        if(!BinaryUtils.isEmpty(voList)){
            return voList.stream().sorted(Comparator.comparing(SysModelVo::getID)).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public List<SysTemplateDto> querySchemeType() {
        DlvrTemplateReq queryBean = new DlvrTemplateReq();
        //已发布
        queryBean.setStatus(Collections.singletonList(3));
        queryBean.setPageNum(1);
        queryBean.setPageSize(3000);
        List<DlvrTemplateVO> templateList = templateService.getDlvrTemplateList(queryBean).getData();
        //查询所有已发布的方案
        if(BinaryUtils.isEmpty(templateList)){
            return new ArrayList<>();
        }
        Map<Long, List<DlvrTemplateVO>> templateMap = templateList.stream().collect(Collectors.groupingBy(DlvrTemplateVO::getProposalType));
        List<SysTemplateDto> sysList = new ArrayList<>();
        for (DlvrTemplateVO templateVO : templateList) {
            SysTemplateDto planDto = new SysTemplateDto();
            List<DlvrTemplateVO> planInstance = templateMap.get(templateVO.getProposalType());
            if(!BinaryUtils.isEmpty(planInstance)){
                planDto.setId(templateVO.getProposalType());
                planDto.setName(templateVO.getProposalName());
                List<DlvrTemplateVO> sortPlanList = planInstance.stream().sorted(Comparator.comparing(DlvrTemplateVO::getCreateTime)).collect(Collectors.toList());
                planDto.setVoList(sortPlanList);
                sysList.add(planDto);
            }
        }
        if(!BinaryUtils.isEmpty(sysList)){
            return sysList.stream().sorted(Comparator.comparing(SysTemplateDto::getId)).distinct().collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public Boolean deleteAssertDir(Long assertDirId) {
        if (assertDirId == null) {
            throw new BusinessException("要删除的资产目录id不能为空");
        }
        Integer integer = categoryDesignDao.deleteById(assertDirId);
        return integer > 0;
    }

}
